<template>
  <view class="task-submit-page">
    <!-- 返回按钮 -->
    <view class="header-back" @click="handleBack">
      <u-icon name="arrow-left" size="24" color="#333333" />
    </view>
    
    <!-- 页面标题 -->
    <view class="page-title">
      <text>提交任务</text>
    </view>
    
    <!-- 任务基本信息 -->
    <view class="task-info-card" v-if="task">
      <text class="task-title">{{ task.title }}</text>
      <view class="task-reward">
        <u-icon name="medal" size="18" color="#ff9500" />
        <text class="reward-points">{{ task.reward_points }} 积分</text>
      </view>
    </view>
    
    <!-- 提交表单 -->
    <u-form 
      ref="submitFormRef" 
      :model="formData" 
      :rules="rules" 
      label-position="left"
      label-width="80px"
    >
      <!-- 文本输入 -->
      <u-form-item 
        v-for="field in textFields" 
        :key="field.name"
        :label="field.label" 
        :prop="field.name"
        :required="field.required"
      >
        <u-input 
          v-model="formData[field.name]" 
          :placeholder="field.placeholder || `请输入${field.label}`"
          :maxlength="field.maxlength || 200"
          :show-word-limit="true"
          :type="field.type || 'text'"
          :disabled="submitting"
        ></u-input>
      </u-form-item>
      
      <!-- 多行文本 -->
      <u-form-item 
        v-for="field in textareaFields" 
        :key="field.name"
        :label="field.label" 
        :prop="field.name"
        :required="field.required"
      >
        <u-input 
          v-model="formData[field.name]" 
          :placeholder="field.placeholder || `请输入${field.label}`"
          :maxlength="field.maxlength || 500"
          :show-word-limit="true"
          type="textarea"
          :rows="field.rows || 4"
          :disabled="submitting"
        ></u-input>
      </u-form-item>
      
      <!-- 图片上传 -->
      <u-form-item 
        v-for="field in uploadFields" 
        :key="field.name"
        :label="field.label" 
        :prop="field.name"
        :required="field.required"
      >
        <u-upload 
          ref="uploadRef"
          v-model="formData[field.name]"
          :action="uploadUrl"
          :header="uploadHeader"
          :name="'file'"
          :max-count="field.maxCount || 3"
          :size-type="['compressed']"
          :width="80"
          :height="80"
          :auto-upload="false"
          @after-read="(file) => handleAfterRead(file, field.name)"
          @delete="(index, file) => handleDelete(index, file, field.name)"
          :disabled="submitting"
        ></u-upload>
        <text class="upload-tip" v-if="field.tip">{{ field.tip }}</text>
      </u-form-item>
      
      <!-- 选择器 -->
      <u-form-item 
        v-for="field in selectorFields" 
        :key="field.name"
        :label="field.label" 
        :prop="field.name"
        :required="field.required"
      >
        <u-select 
          v-model="formData[field.name]"
          :list="field.options"
          :multiple="field.multiple || false"
          :confirm-button-text="'确定'"
          :cancel-button-text="'取消'"
          :disabled="submitting"
          @confirm="(res) => handleSelectorConfirm(res, field.name)"
        >
          <view class="selector-trigger">
            <text 
              class="selector-text"
              :class="{ 'placeholder': !formData[field.name] }"
            >
              {{ getSelectorText(field.name, field.options) || (field.placeholder || `请选择${field.label}`) }}
            </text>
            <u-icon name="arrow-right" size="18" color="#999999" />
          </view>
        </u-select>
      </u-form-item>
    </u-form>
    
    <!-- 提交须知 -->
    <view class="submit-notice">
      <view class="notice-title">
        <u-icon name="warning-circle" size="16" color="#ff9500" />
        <text>提交须知</text>
      </view>
      <view class="notice-content">
        <text class="notice-item">• 请确保提交内容真实有效</text>
        <text class="notice-item">• 提交后将由管理员审核</text>
        <text class="notice-item">• 审核通过后将发放积分奖励</text>
        <text class="notice-item">• 每个任务只能提交一次</text>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="submit-button-wrapper">
      <u-button 
        type="primary" 
        size="large"
        :loading="submitting"
        :disabled="submitting || formData.isSubmitted"
        @click="handleSubmit"
      >
        {{ submitting ? '提交中...' : '提交任务' }}
      </u-button>
      
      <u-button 
        v-if="formData.isSubmitted" 
        type="success" 
        size="large"
        disabled
      >
        已提交，等待审核
      </u-button>
    </view>
    
    <!-- 提示弹窗 -->
    <u-toast ref="toastRef" />
    
    <!-- 加载中 -->
    <u-loading-page v-if="loading" color="#409eff"></u-loading-page>
  </view>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { useTaskStore } from '../../store/task.js';
import { useUserStore } from '../../store/user.js';
import { uploadFile } from '../../api/request.js';

export default defineComponent({
  name: 'TaskSubmit',
  setup() {
    const taskStore = useTaskStore();
    const userStore = useUserStore();
    
    // 状态管理
    const loading = ref(true);
    const submitting = ref(false);
    const submitFormRef = ref(null);
    const uploadRef = ref(null);
    const taskId = ref('');
    const uploadUrls = ref([]); // 存储上传的文件URL
    
    // 表单数据
    const formData = reactive({
      task_id: '',
      description: '',
      screenshots: [],
      link: '',
      contact_info: '',
      isSubmitted: false
    });
    
    // 表单验证规则
    const rules = reactive({
      description: [
        { required: true, message: '请描述任务完成情况', trigger: 'blur' }
      ],
      screenshots: [
        {
          required: true,
          message: '请上传至少一张截图',
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value.length === 0) {
              callback(new Error('请上传至少一张截图'));
            } else {
              callback();
            }
          }
        }
      ]
    });
    
    // 获取任务详情
    const task = computed(() => taskStore.currentTask);
    
    // 上传配置
    const uploadUrl = computed(() => {
      // 实际项目中配置上传接口地址
      return '/api/upload/image';
    });
    
    const uploadHeader = computed(() => {
      return {
        'Authorization': `Bearer ${userStore.token}`
      };
    });
    
    // 表单字段定义
    const textFields = [
      {
        name: 'link',
        label: '相关链接',
        placeholder: '请输入任务相关的链接（选填）',
        required: false,
        type: 'url'
      },
      {
        name: 'contact_info',
        label: '联系方式',
        placeholder: '请输入您的联系方式',
        required: false,
        maxlength: 50
      }
    ];
    
    const textareaFields = [
      {
        name: 'description',
        label: '完成说明',
        placeholder: '请详细描述您是如何完成任务的',
        required: true,
        maxlength: 500,
        rows: 5
      }
    ];
    
    const uploadFields = [
      {
        name: 'screenshots',
        label: '任务截图',
        required: true,
        maxCount: 5,
        tip: '请上传任务完成的截图，最多5张'
      }
    ];
    
    const selectorFields = [
      // 可以根据实际需求添加选择器字段
    ];
    
    // 加载任务详情和用户提交状态
    const loadTaskInfo = async (id) => {
      if (!id) return;
      
      try {
        loading.value = true;
        formData.task_id = id;
        
        // 加载任务详情
        await taskStore.fetchTaskDetail(id);
        
        // 检查用户是否已提交过
        if (userStore.isLoggedIn && taskStore.currentTask) {
          formData.isSubmitted = taskStore.currentTask.is_submitted || false;
        }
      } catch (error) {
        console.error('加载任务信息失败:', error);
        uni.showToast({
          title: '加载失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        loading.value = false;
      }
    };
    
    // 处理文件选择
    const handleAfterRead = async (file, fieldName) => {
      try {
        // 显示加载中
        file.status = 'uploading';
        file.message = '上传中...';
        
        // 上传文件
        const result = await uploadFile({
          url: uploadUrl.value,
          filePath: file.url,
          name: 'file',
          header: uploadHeader.value,
          formData: {
            file: file,
            type: 'task_submit'
          }
        });
        
        // 模拟上传成功（实际项目中根据接口返回处理）
        setTimeout(() => {
          file.status = 'success';
          // 保存上传后的URL
          const index = formData[fieldName].findIndex(item => item.uid === file.uid);
          if (index !== -1) {
            // 这里使用模拟的URL，实际应该使用接口返回的URL
            formData[fieldName][index].url = file.url;
            uploadUrls.value.push(file.url);
          }
        }, 1000);
      } catch (error) {
        console.error('文件上传失败:', error);
        file.status = 'fail';
        file.message = '上传失败';
        
        uni.showToast({
          title: '文件上传失败，请重试',
          icon: 'none'
        });
      }
    };
    
    // 处理文件删除
    const handleDelete = (index, file, fieldName) => {
      // 从上传URLs中移除
      const urlIndex = uploadUrls.value.indexOf(file.url);
      if (urlIndex !== -1) {
        uploadUrls.value.splice(urlIndex, 1);
      }
    };
    
    // 处理选择器确认
    const handleSelectorConfirm = (res, fieldName) => {
      formData[fieldName] = res.value;
    };
    
    // 获取选择器显示文本
    const getSelectorText = (fieldName, options) => {
      const value = formData[fieldName];
      if (!value) return '';
      
      if (Array.isArray(value)) {
        return value.map(v => {
          const option = options.find(opt => opt.value === v);
          return option ? option.label : '';
        }).join(', ');
      } else {
        const option = options.find(opt => opt.value === value);
        return option ? option.label : '';
      }
    };
    
    // 验证表单
    const validateForm = () => {
      return new Promise((resolve, reject) => {
        submitFormRef.value.validate((valid, errors) => {
          if (valid) {
            resolve();
          } else {
            // 显示第一个错误
            const firstError = Object.values(errors)[0][0];
            uni.showToast({
              title: firstError.message,
              icon: 'none'
            });
            reject(firstError);
          }
        });
      });
    };
    
    // 提交任务
    const handleSubmit = async () => {
      try {
        // 验证表单
        await validateForm();
        
        submitting.value = true;
        
        // 准备提交数据
        const submitData = {
          task_id: formData.task_id,
          description: formData.description,
          screenshots: uploadUrls.value,
          link: formData.link,
          contact_info: formData.contact_info
        };
        
        // 调用提交任务接口
        const result = await taskStore.submitTask(submitData);
        
        if (result && result.success) {
          uni.showToast({
            title: '提交成功，等待审核',
            icon: 'success'
          });
          
          // 更新提交状态
          formData.isSubmitted = true;
          
          // 延迟返回
          setTimeout(() => {
            handleBack();
          }, 1500);
        } else {
          uni.showToast({
            title: result.message || '提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('提交任务失败:', error);
        uni.showToast({
          title: '提交失败，请稍后重试',
          icon: 'none'
        });
      } finally {
        submitting.value = false;
      }
    };
    
    // 返回上一页
    const handleBack = () => {
      uni.navigateBack();
    };
    
    // 生命周期
    onMounted(() => {
      // 检查登录状态
      if (!userStore.isLoggedIn) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
        return;
      }
      
      // 获取任务ID
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      taskId.value = currentPage.options.id || '';
      
      // 加载任务信息
      if (taskId.value) {
        loadTaskInfo(taskId.value);
      } else {
        loading.value = false;
        uni.showToast({
          title: '任务ID不存在',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }
    });
    
    return {
      loading,
      submitting,
      submitFormRef,
      uploadRef,
      formData,
      rules,
      task,
      uploadUrl,
      uploadHeader,
      textFields,
      textareaFields,
      uploadFields,
      selectorFields,
      handleAfterRead,
      handleDelete,
      handleSelectorConfirm,
      getSelectorText,
      handleSubmit,
      handleBack
    };
  }
});
</script>

<style lang="scss" scoped>
.task-submit-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100px; // 为底部按钮留出空间
  
  .header-back {
    position: fixed;
    top: 16px;
    left: 16px;
    z-index: 10;
    background-color: rgba(255, 255, 255, 0.9);
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .page-title {
    text-align: center;
    margin-bottom: 20px;
    
    text {
      font-size: 18px;
      font-weight: 600;
      color: #333333;
    }
  }
}

.task-info-card {
  background-color: #ffffff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .task-title {
    display: block;
    font-size: 16px;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8px;
    line-height: 1.4;
  }
  
  .task-reward {
    display: flex;
    align-items: center;
    
    .reward-points {
      font-size: 16px;
      font-weight: 600;
      color: #ff9500;
      margin-left: 6px;
    }
  }
}

:deep() {
  .u-form {
    background-color: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    
    .u-form-item {
      margin-bottom: 16px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .u-label {
        font-size: 14px;
        color: #333333;
        padding-right: 8px;
      }
      
      .u-input__wrapper {
        border-radius: 8px;
      }
      
      .u-input__area {
        min-height: 36px;
      }
      
      .u-input__textarea {
        min-height: 100px;
      }
    }
  }
  
  .u-upload {
    margin-top: 8px;
  }
}

.upload-tip {
  display: block;
  font-size: 12px;
  color: #999999;
  margin-top: 4px;
}

.selector-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #ffffff;
  min-height: 36px;
  
  .selector-text {
    font-size: 14px;
    color: #333333;
    
    &.placeholder {
      color: #cccccc;
    }
  }
}

.submit-notice {
  background-color: #fff8e6;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
  
  .notice-title {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    
    text {
      font-size: 14px;
      font-weight: 600;
      color: #ff9500;
      margin-left: 6px;
    }
  }
  
  .notice-content {
    .notice-item {
      display: block;
      font-size: 13px;
      color: #ff9500;
      line-height: 1.5;
      margin-bottom: 4px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.submit-button-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  z-index: 9;
  
  :deep() {
    .u-button {
      width: 100%;
      height: 44px;
      font-size: 16px;
    }
  }
}

// 响应式适配
@media screen and (min-width: 768px) {
  .task-submit-page {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
    padding-bottom: 120px;
  }
  
  .header-back {
    position: relative;
    top: auto;
    left: auto;
    margin-bottom: 16px;
  }
}

// 深色模式适配
:global(.dark-theme) .task-submit-page {
  background-color: #1a1a1a;
  
  .header-back {
    background-color: rgba(42, 42, 42, 0.9);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    
    :deep() .u-icon {
      color: #ffffff !important;
    }
  }
  
  .page-title {
    text {
      color: #ffffff;
    }
  }
  
  .task-info-card {
    background-color: #2a2a2a;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    
    .task-title {
      color: #ffffff;
    }
  }
  
  :deep() {
    .u-form {
      background-color: #2a2a2a;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
      
      .u-label {
        color: #ffffff;
      }
      
      .u-input__wrapper {
        background-color: #3a3a3a;
        border-color: #4a4a4a;
        
        .u-input__area input,
        .u-input__textarea {
          color: #ffffff;
        }
      }
    }
  }
  
  .selector-trigger {
    background-color: #3a3a3a;
    border-color: #4a4a4a;
    
    .selector-text {
      color: #ffffff;
      
      &.placeholder {
        color: #666666;
      }
    }
  }
  
  .submit-notice {
    background-color: #3a2c1b;
    
    .notice-title {
      text {
        color: #ffc107;
      }
    }
    
    .notice-content {
      .notice-item {
        color: #ffc107;
      }
    }
  }
  
  .submit-button-wrapper {
    background-color: #2a2a2a;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.3);
  }
}
</style>